package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.api.wemedia.IWemediaClient;
import com.zhentao.common.constants.ArticleConstants;
import com.zhentao.mapper.ArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.article.vo.HotArticleVo;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.wemwdia.pojo.WmChannel;
import com.zhentao.service.HotArticleService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public void computeHotArticle() {
        //1.查询前5天的文章数据
        Date dateParam= DateTime.now().minusDays(50).toDate();
        List<ApArticle> list = articleMapper.findArticleListByLast5days(dateParam);
        //2.计算文章的分值
        List<HotArticleVo> hotArticleVos = computeHotArticle(list);
        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVos);

    }


    /**
     * 为每个频道缓存30条分值较高的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList){
        ResponseResult result = wemediaClient.getChannels();
        if (result.getCode().equals(200)) {
            String json = JSON.toJSONString(result.getData());
            List<WmChannel> wmChannels = JSON.parseArray(json, WmChannel.class);
            //检索出每个频道的文章
            if(wmChannels != null && wmChannels.size()>0){
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> collect = hotArticleVoList.stream().filter(hotArticleVo ->
                            hotArticleVo.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
                    //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
                    sortAndCache(collect,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId());
                }
            }
        }
        sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 计算文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleList){
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        if(apArticleList != null && apArticleList.size()>0){
            for (ApArticle apArticle : apArticleList) {
                HotArticleVo hot=new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hot);
                Integer score = computeScore(apArticle);
                hot.setScore(score);
                hotArticleVoList.add(hot);
            }
        }
        return hotArticleVoList;
    }
    /**
     * 排序并且缓存数据
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if(hotArticleVos.size()>=30){
            hotArticleVos = hotArticleVos.subList(0,30);
        }
        redisTemplate.opsForValue().set(key,JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle){
        Integer scere=0;
        if(apArticle.getLikes() != 0){
            scere += ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT*apArticle.getLikes();
        }
        if(apArticle.getCollection() != 0){
            scere +=apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        if(apArticle.getViews() != 0){
            scere+=apArticle.getViews();
        }
        if(apArticle.getComment() != 0){
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return scere;
    }
}
